<template>
	<div class="w80 center">
		<!-- <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable> -->
		<el-form ref="dataFormRef" size="large" :model="form" :rules="dataRules" formDialogRef label-width="120px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="12" class="mb20">
					<el-form-item label="社保卡号" prop="medicalCard">
						<el-input v-model="form.medicalCard" placeholder="请输入社保卡号">
							<template #append>
								<el-button type="primary" @click="readCard">读卡</el-button>
							</template>
						</el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="身份证号" prop="icCard">
						<el-input v-model="form.icCard" placeholder="请输入身份证号" @input="inputIcCard" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="姓名" prop="name">
						<el-input v-model="form.name" autocomplete="off" placeholder="请输入姓名">
							<template #append>
								<el-popover placement="bottom" :width="700" trigger="click" ref="popoverRef">
									<template #reference>
										<el-button type="primary" @click="searchData" v-auth="'xt_name_query'">查询</el-button>
									</template>
									<div>
										<el-form-item label="姓名：" label-width="60" style="text-align: left">
											<el-input v-model="userName" @input="inputName" autocomplete="off" placeholder="请输入姓名"> </el-input>
										</el-form-item>
									</div>
									<el-table :data="gridData" height="300" @row-dblclick="dbclick">
										<el-table-column width="120" property="name" label="姓名" show-overflow-tooltip />
										<el-table-column width="60" property="age" label="年龄" show-overflow-tooltip />
										<el-table-column width="80" property="sex" label="性别" show-overflow-tooltip>
											<template #default="scope">
												<el-tag size="small" v-if="scope.row.sex === '1'">男</el-tag>
												<el-tag size="small" v-if="scope.row.sex === '2'">女</el-tag>
											</template>
										</el-table-column>
										<el-table-column width="180" property="icCard" label="身份证号" show-overflow-tooltip />
										<el-table-column width="120" property="villageName" label="村" show-overflow-tooltip />
										<el-table-column width="" property="address" label="家庭地址" show-overflow-tooltip />
									</el-table>
								</el-popover>
							</template>
						</el-input>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="出生日期" prop="birthday">
						<el-date-picker type="date" placeholder="请选择出生日期" v-model="form.birthday" :value-format="dateStr"></el-date-picker>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="年龄" prop="age">
						<el-input-number v-model="form.age" placeholder="请输入年龄"></el-input-number>
					</el-form-item>
				</el-col>

				<!--        <el-col :span="12" class="mb20">-->
				<!--          <el-form-item label="性别" prop="sex">-->
				<!--            <el-radio-group v-model="form.sex">-->
				<!--              <el-radio :label="item.value" v-for="(item, index) in gender" border :key="index">{{-->
				<!--                  item.label-->
				<!--                }}-->
				<!--              </el-radio>-->
				<!--            </el-radio-group>-->
				<!--          </el-form-item>-->
				<!--        </el-col>-->
				<el-col :span="12" class="mb20">
					<el-form-item label="家庭医生" prop="familyDoctor">
						<!-- <el-select v-model="form.familyDoctor" placeholder="请输入家庭医生">
  <el-option :label="item.label" :value="item.value" v-for="(item, index) in family_doctor" :key="index" />
</el-select> -->
						{{ form.doctorName }}
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12" class="mb20">
            <el-form-item label="联系电话" prop="tel">
                <el-input v-model="form.tel" placeholder="请输入联系电话"></el-input>
            </el-form-item>
        </el-col> -->

				<!--        <el-col :span="12" class="mb20">-->
				<!--          <el-form-item label="村" prop="village">-->
				<!--            <el-input v-model="form.village" placeholder="请输入村"/>-->
				<!--          </el-form-item>-->

				<!--          <el-form-item label="村" prop="village">-->
				<!--            <el-select v-model="form.village" placeholder="请输入村" @change="handleChangeVillage">-->
				<!--              <el-option :label="item.name" :value="item.id" v-for="(item, index) in village"-->
				<!--                         :key="index"/>-->
				<!--            </el-select>-->
				<!--          </el-form-item>-->
				<!--        </el-col>-->

				<!-- <el-col :span="12" class="mb20">
            <el-form-item label="卡号" prop="localCard">
                <el-input v-model="form.localCard" placeholder="请输入卡号" />
            </el-form-item>
        </el-col> -->

				<el-col :span="12" class="mb20">
					<el-form-item label="是否空腹" prop="isFasting">
						<el-radio-group v-model="form.isFasting">
							<el-radio :label="item.value" v-for="(item, index) in bloodx_fasting" border :key="index">{{ item.label }} </el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="家庭地址" prop="address">
						{{ form.address }}
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="检测时间" prop="detectionTime">
						<el-date-picker type="datetime" placeholder="请选择检测时间" v-model="form.detectionTime" :value-format="dateTimeStr"></el-date-picker>
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="村" prop="villageName">
						{{ form.villageName }}
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="血糖值" prop="number">
						<el-input v-model="form.number" placeholder="请输入血糖值" />
					</el-form-item>
				</el-col>

				<el-col :span="12" class="mb20">
					<el-form-item label="录入次数" prop="inputNum">
						{{ form.inputNum }}
					</el-form-item>
				</el-col>
				<!-- <el-col :span="12" class="mb20">
            <el-form-item label="管理状态" prop="healthStatus">
                <el-radio-group v-model="form.healthStatus">
                    <el-radio :label="item.value" v-for="(item, index) in bloodx_health" border :key="index">{{
    item.label }}
                    </el-radio>
                </el-radio-group>
            </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
            <el-form-item label="次数" prop="examNum">
                <el-input v-model="form.examNum" placeholder="请输入次数" />
            </el-form-item>
        </el-col> -->
			</el-row>
			<el-row>
				<el-col :span="24" class="mb20">
					<el-form-item>
						<el-button @click="clear">清空</el-button>
						<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
	</div>
</template>

<script setup lang="ts" name="BloodxCustomerDialog">
import { ref, reactive } from 'vue';
import { useDict } from '/@/hooks/dict';
import { useMessage } from '/@/hooks/message';
// import { getObj, addObj, putObj, sysVillageList } from '/@/api/blood/bloodxCustomer';
import { rule } from '/@/utils/validate';
// import {readCardDevice} from '/@/utils/ajaxUtil';
import { fetchList, fetchListGlucose, sysVillageList } from '/@/api/blood/bloodxCustomer';

const emit = defineEmits(['refresh']);
const { bloodx_fasting } = useDict('bloodx_fasting');
import { addObj } from '/@/api/blood/bloodxCustomerBlood';
import { dayjs, ElMessageBox } from 'element-plus';
// 定义变量内容
const dataFormRef = ref();
const visible = ref(true);
// const visiblePopover = ref(false);
const loading = ref(false);
const village = ref([]);
const readCardWs = ref(null);
const gridData = ref([]);

const popoverRef = ref(null);

const userName = ref('');

const inputTimer = ref(null);

sysVillageList().then((res) => {
	village.value = res.data;
});
// 定义字典
// const {gender, bloodx_health, family_doctor} = useDict('gender', 'bloodx_health', 'family_doctor');
// const getNowDateTimer = ref(null);
// 提交表单数据
const form = reactive({
	id: '',
	name: '',
	birthday: '',
	age: null,
	sex: '',
	examNum: '',
	icCard: '',
	tel: '',
	address: '',
	village: '',
	localCard: '',
	doctorName: '',
	medicalCard: '',
	healthStatus: '0',
	familyDoctor: '',
	number: '',
	detectionTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
	isFasting: '',
	customerId: '',
	villageName: '',
	inputNum: 0,
});

// onMounted(() => {
//   form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
// });

// const focusTime = () => {
//   clearInterval(getNowDateTimer.value)
// }
//
// const blurTime = () => {
//   getNowDate()
// }
// form.detectionTime实时获取当前时间

const clear = () => {
	form.id = '';
	form.name = '';
	form.birthday = '';
	form.age = null;
	form.sex = '';
	form.examNum = '';
	form.icCard = '';
	form.tel = '';
	form.address = '';
	form.village = '';
	form.localCard = '';
	form.doctorName = '';
	form.medicalCard = '';
	form.healthStatus = '0';
	form.familyDoctor = '';
	form.number = '';
	form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
	form.isFasting = '';
	form.customerId = '';
	form.villageName = '';
	form.inputNum = 0;
}; // 清空表单数据
const resetForm = () => {
	form.id = '';
	form.name = '';
	form.birthday = '';
	form.age = null;
	form.sex = '';
	form.examNum = '';
	form.icCard = '';
	form.tel = '';
	form.address = '';
	form.village = '';
	form.localCard = '';
	form.doctorName = '';
	// form.medicalCard = '';
	form.healthStatus = '0';
	form.familyDoctor = '';
	form.number = '';
	form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
	form.isFasting = '';
	form.customerId = '';
	form.villageName = '';
	form.inputNum = 0;
};

// 定义校验规则
const dataRules = ref({
	// name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
	age: [{ validator: rule.number, trigger: 'blur' }],
	tel: [{ validator: rule.mobilePhone, trigger: 'blur' }],
	isFasting: [{ required: true, message: '请选择是否空腹', trigger: 'change' }],
	number: [{ required: true, message: '请输入血糖值', trigger: 'blur' }],
	detectionTime: [{ required: true, message: '请选择检测时间', trigger: 'change' }],

	// village: [{required: true, message: '请选择村', trigger: 'blur'}],
});
// 销毁组件时清除定时器
onBeforeUnmount(() => {
	if (readCardWs.value) {
		readCardWs.value.close();
	}
	if (inputTimer.value) {
		clearTimeout(inputTimer.value);
	}
});

const inputName = (val: string) => {
	if (inputTimer.value) {
		clearTimeout(inputTimer.value);
	}

	if (val === '') {
		gridData.value = [];
		return;
	}
	const data = {
		current: 1,
		size: 100,
		name: userName.value,
	};

	inputTimer.value = setTimeout(() => {
		fetchListGlucose(data).then((res) => {
			if (res.data.records.length === 0) {
				gridData.value = [];
				return;
			}
			gridData.value = res.data.records;
		});
	}, 500);
};

const searchData = () => {
	gridData.value = [];
	userName.value = '';
	if (form.name) {
		userName.value = form.name;
		inputName(userName.value);
	}
};

const dbclick = (row: any) => {
	if (row.inputNum >= 1) {
		ElMessageBox.confirm(
			`<p style="font-size: 22px;color: #000;">
            此居民已在本月${row.controlsTime ? row.controlsTime.substring(5, 10) : ''}
            完成一次免费血糖监测，${row.controlsName ? '监测人：' + row.controlsName + '，' : ''}是否继续录入？
        </p>`,
			{
				dangerouslyUseHTMLString: true,
				confirmButtonText: '确认',
				cancelButtonText: '取消',
				type: 'warning',
			}
		)
			.then(() => {
				form.medicalCard = row.medicalCard;
				form.address = row.address;
				form.age = row.age;
				form.name = row.name;
				form.birthday = row.birthday;
				form.examNum = row.examNum;
				form.icCard = row.icCard;
				form.tel = row.tel;
				form.village = row.village;
				form.localCard = row.localCard;
				form.doctorName = row.doctorName;
				form.sex = row.sex;
				form.familyDoctor = row.familyDoctor;
				form.customerId = row.id;
				form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
				form.villageName = row.villageName;
				form.inputNum = row.inputNum;
			})
			.catch(() => {
				return;
			});
	} else {
		form.medicalCard = row.medicalCard;
		form.address = row.address;
		form.age = row.age;
		form.name = row.name;
		form.birthday = row.birthday;
		form.examNum = row.examNum;
		form.icCard = row.icCard;
		form.tel = row.tel;
		form.village = row.village;
		form.localCard = row.localCard;
		form.doctorName = row.doctorName;
		form.sex = row.sex;
		form.familyDoctor = row.familyDoctor;
		form.customerId = row.id;
		form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
		form.villageName = row.villageName;
		form.inputNum = row.inputNum;
	}

	popoverRef.value.hide();
};

// 读卡
const readCard = async () => {
	//   清空表单数据
	resetForm();
	form.detectionTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
	loading.value = true;
	// 清空表单数据

	try {
		if (form.medicalCard != '') {
			// console.log(111)
			const data = {
				current: 1,
				size: 20,
				medicalCard: form.medicalCard,
			};
			// dataFormRef.value?.resetFields();
			fetchListGlucose(data).then((res) => {
				if (res.data.records.length === 0) {
					useMessage().error('未查询到相关信息');
					return;
				}

				if (res.data.records[0].inputNum >= 1) {
					let row = res.data.records[0];
					ElMessageBox.confirm(
						`<p style="font-size: 22px;color: #000;">
            此居民已在本月${row.controlsTime ? row.controlsTime.substring(5, 10) : ''}
            完成一次免费血糖监测，${row.controlsName ? '监测人：' + row.controlsName + '，' : ''}是否继续录入？
        </p>`,
						{
							dangerouslyUseHTMLString: true,
							confirmButtonText: '确认',
							cancelButtonText: '取消',
							type: 'warning',
						}
					)
						.then(() => {
							form.medicalCard = res.data.records[0].medicalCard;
							form.address = res.data.records[0].address;
							form.age = res.data.records[0].age;
							form.name = res.data.records[0].name;
							form.birthday = res.data.records[0].birthday;
							form.examNum = res.data.records[0].examNum;
							form.icCard = res.data.records[0].icCard;
							form.tel = res.data.records[0].tel;
							form.village = res.data.records[0].village;
							form.localCard = res.data.records[0].localCard;
							form.doctorName = res.data.records[0].doctorName;
							// form.doctorName = res.data.records[0].doctorName
							form.sex = res.data.records[0].sex;
							form.familyDoctor = res.data.records[0].familyDoctor;
							form.customerId = res.data.records[0].id;
							form.villageName = res.data.records[0].villageName;
							form.inputNum = res.data.records[0].inputNum;
						})
						.catch(() => {
							return;
						});
				} else {
					form.medicalCard = res.data.records[0].medicalCard;
					form.address = res.data.records[0].address;
					form.age = res.data.records[0].age;
					form.name = res.data.records[0].name;
					form.birthday = res.data.records[0].birthday;
					form.examNum = res.data.records[0].examNum;
					form.icCard = res.data.records[0].icCard;
					form.tel = res.data.records[0].tel;
					form.village = res.data.records[0].village;
					form.localCard = res.data.records[0].localCard;
					form.doctorName = res.data.records[0].doctorName;
					// form.doctorName = res.data.records[0].doctorName
					form.sex = res.data.records[0].sex;
					form.familyDoctor = res.data.records[0].familyDoctor;
					form.customerId = res.data.records[0].id;
					form.villageName = res.data.records[0].villageName;
					form.inputNum = res.data.records[0].inputNum;
				}
			});
		} else {
			sendReadCard('ws://127.0.0.1:2018', (message) => {
				if (JSON.parse(message).Data.IsSuccess === false) {
					useMessage().error(JSON.parse(message).Data.msg);
					return;
				}
				let list = JSON.parse(message).Data.kh.split('|');
				// console.log(list);
				const data = {
					current: 1,
					size: 20,
					// name: list[4],
					medicalCard: list[2],
				};
				fetchListGlucose(data).then((res) => {
					if (res.data.records.length === 0) {
						useMessage().error('未查询到相关信息');
						return;
					}

					if (res.data.records[0].inputNum >= 1) {
						let row = res.data.records[0];
						ElMessageBox.confirm(
							`<p style="font-size: 22px;color: #000;">
            此居民已在本月${row.controlsTime ? row.controlsTime.substring(5, 10) : ''}
            完成一次免费血糖监测，${row.controlsName ? '监测人：' + row.controlsName + '，' : ''}是否继续录入？
        </p>`,
							{
								dangerouslyUseHTMLString: true,
								confirmButtonText: '确认',
								cancelButtonText: '取消',
								type: 'warning',
							}
						)
							.then(() => {
								form.medicalCard = res.data.records[0].medicalCard;
								form.address = res.data.records[0].address;
								form.age = res.data.records[0].age;
								form.name = res.data.records[0].name;
								form.birthday = res.data.records[0].birthday;
								form.examNum = res.data.records[0].examNum;
								form.icCard = res.data.records[0].icCard;
								form.tel = res.data.records[0].tel;
								form.village = res.data.records[0].village;
								form.localCard = res.data.records[0].localCard;
								form.doctorName = res.data.records[0].doctorName;
								// form.doctorName = res.data.records[0].doctorName
								form.sex = res.data.records[0].sex;
								form.familyDoctor = res.data.records[0].familyDoctor;
								form.customerId = res.data.records[0].id;
								form.villageName = res.data.records[0].villageName;
								form.inputNum = res.data.records[0].inputNum;
							})
							.catch(() => {
								return;
							});
					} else {
						form.medicalCard = res.data.records[0].medicalCard;
						form.address = res.data.records[0].address;
						form.age = res.data.records[0].age;
						form.name = res.data.records[0].name;
						form.birthday = res.data.records[0].birthday;
						form.examNum = res.data.records[0].examNum;
						form.icCard = res.data.records[0].icCard;
						form.tel = res.data.records[0].tel;
						form.village = res.data.records[0].village;
						form.localCard = res.data.records[0].localCard;
						form.doctorName = res.data.records[0].doctorName;
						// form.doctorName = res.data.records[0].doctorName
						form.sex = res.data.records[0].sex;
						form.familyDoctor = res.data.records[0].familyDoctor;
						form.customerId = res.data.records[0].id;
						form.villageName = res.data.records[0].villageName;
						form.inputNum = res.data.records[0].inputNum;
					}

					// console.log(res.data)
					// form.medicalCard = res.data.records[0].medicalCard
					// form.name = res.data.records[0].name
					// form.birthday = res.data.records[0].birthday
					// form.sex = res.data.records[0].sex
					// form.age = res.data.records[0].age
					// form.healthStatus = res.data.records[0].healthStatus
					// form.village = res.data.records[0].villageName
					// form.familyDoctor = res.data.records[0].familyDoctor
					// form.customerId = res.data.records[0].id
					// form.villageName = res.data.records[0].villageName
				});
			});
		}

		// const readRes = await sendReadCard();
		// if (readRes.code == 0) {
		// 	useMessage().success(readRes.msg);
		// 	form.name = '张三';
		// 	form.birthday = '1990-01-01';
		// 	form.age = 30;
		// 	form.medicalCard = readRes.data;
		// }
	} finally {
		loading.value = false;
	}
};
const sendReadCard = (WSURL: any, callback: any) => {
	if (readCardWs.value !== null) {
		if (readCardWs.value.readyState === 0 || readCardWs.value.readyState === 1) {
			return;
		} else {
			readCardWs.value.close();
		}
	}
	readCardWs.value = new WebSocket(WSURL);
	readCardWs.value.addEventListener('open', () => {
		readCardWs.value.send('读卡');
	});

	readCardWs.value.addEventListener('close', () => {});

	readCardWs.value.addEventListener('error', () => {
		readCardWs.value.close();
		useMessage().error('读卡失败');
	});

	readCardWs.value.addEventListener('message', (message) => {
		if (message.data !== 'Open!') {
			readCardWs.value.close();
			callback(message.data);
		}
	});
};
const handleChangeVillage = (id: Object) => {
	// console.log(village.value)
	form.familyDoctor = village.value.find((item) => item.id === id).doctorId;
	form.doctorName = village.value.find((item) => item.id === id).doctorName;
};

const inputIcCard = (val: string) => {
	if (val.length === 18) {
		form.birthday = val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14);
		form.sex = parseInt(val.substring(16, 17)) % 2 === 0 ? '2' : '1';
		form.age = new Date().getFullYear() - parseInt(val.substring(6, 10));
	}
};
// 打开弹窗
const openDialog = (id: string) => {
	visible.value = true;
	form.id = '';
	sysVillageList().then((res) => {
		village.value = res.data;
	});
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
	});

	// 获取bloodxCustomer信息
	if (id) {
		form.id = id;
		getbloodxCustomerData(id);
	}
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;

	try {
		loading.value = true;
		await addObj(form);
		useMessage().success('添加成功');
		visible.value = false;
		//   清空表单数据
		clear();
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 初始化表单数据
const getbloodxCustomerData = (id: string) => {
	// 获取数据
	loading.value = true;
	getObj(id)
		.then((res: any) => {
			Object.assign(form, res.data);
		})
		.finally(() => {
			loading.value = false;
		});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped>
.center {
	position: absolute;
	width: 50%;
	left: 50%;
	top: 50%;
	transform: translateY(-50%) translateX(-50%);
}

.radius {
	border: 1px solid var(--el-border-color);
	margin-top: 20px;
	border-radius: 4px;
}

.el-input-group__append button.el-button {
	border-top-left-radius: 0;
	border-bottom-left-radius: 0;
	border-color: var(--el-color-primary);
	background-color: var(--el-color-primary);
	color: var(--el-color-white);
}
</style>
